package routers

import (
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"gspeed/app/dist"
	"gspeed/app/http/middleware"
	"gspeed/app/utils/response"
	"gspeed/bootstrap/global"
	"net/http"
)

func ApiRouter() *gin.Engine {

	router := gin.Default()
	// 是否开启性能分析
	global.Config.SetDefault("app.pprof", false)
	if global.Config.GetBool("app.pprof") {
		pprof.Register(router)
	}

	// 没找到路由
	router.NoRoute(func(c *gin.Context) {
		response.Err(c, response.WithHttpStatus(http.StatusNotFound), response.WithCode(dist.MessageRouterNotFound))
		return
	})
	// 没找到方法
	router.NoMethod(func(c *gin.Context) {
		response.Err(c, response.WithHttpStatus(http.StatusNotFound), response.WithCode(dist.MessageRouterNotFoundMethod))
		return
	})

	//根据配置进行设置跨域
	if global.Config.GetBool("httpServer.AllowCrossDomain") {
		router.Use(middleware.Cors())
	}

	//  创建一个api接口路由组
	vApi := router.Group("/api")
	{
		// 使用jwt中间件
		vApi.Use(global.GinJwt.MiddlewareFunc())
		// 使用casbin中间件 校验权限
		vApi.Use(middleware.Permission())
		// 限速中间件
		vApi.Use(middleware.RateLimit())

	}

	return router
}
